<template>
  <div class="wangeditor-container">
    <Toolbar 
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      v-model="localContent"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      style="height: 500px; border: 1px solid #eee;"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import { ref, shallowRef, watch, onBeforeUnmount } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import axios from 'axios';
import { useLoginEmpStore } from '../../stores/loginEmp';
const loginEmpStore = useLoginEmpStore();

const props = defineProps({
  // 接收原始 HTML 内容
  rawContent: {
    type: String,
    default: ''
  },
  
  // 是否自动渲染 HTML (默认 true)
  renderHtml: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['update:rawContent', 'contentChanged'])

const editorRef = shallowRef()
const localContent = ref(props.rawContent)

// 同步外部传入的内容
watch(() => props.rawContent, (newVal) => {
  if (newVal !== localContent.value) {
    localContent.value = newVal
  }
})

// 双向绑定：内容变化时通知父组件
watch(localContent, (val) => {
  emit('update:rawContent', val)
  emit('contentChanged', val) // 额外的内容变化事件
})

// 编辑器配置
const toolbarConfig = {}

const editorConfig = {
  placeholder: '输入文本内容...',
  //  // 不过滤任何 HTML 标签和属性
  // // 这是关键配置，确保样式标签不会被过滤
  // HTML_PARSER: (html) => html,
  
  // // 允许所有标签和属性
  // HANDLE_PARSE_HTML: (domNode, htmlNode) => {
  //   return {
  //     shouldKeep: true,
  //     node: domNode
  //   }
  // },
  MENU_CONF: {
       uploadImage: {
          server: '/travel/products/upload',
          fieldName: 'file',
          maxFileSize: 5 * 1024 * 1024,
          allowedFileTypes: ['image/jpeg', 'image/png', 'image/gif'],
          headers: () => {
            // 从 Vuex、Pinia 或其他状态管理中获取 token
            // 或者直接从 localStorage 中获取
            const token = loginEmpStore.getLoginEmp();
            return token ? { 'Authorization': `Bearer ${token}` } : {};
          }
    }

  }
}

const mode = 'default'

const handleCreated = (editor) => {
  editorRef.value = editor
  // 编辑器创建完成后，设置初始 HTML 内容
  // if (localContent.value) {
  //   editor.setHtml(localContent.value)
  // }
}

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor) editor.destroy()
})
</script>